package com.chyong.iptv;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.leanback.widget.OnChildViewHolderSelectedListener;
import androidx.leanback.widget.VerticalGridView;
import androidx.recyclerview.widget.RecyclerView;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.chyong.iptv.adapters.ChannelAdapter;
import com.chyong.iptv.beans.Channel;
import com.chyong.iptv.utils.CacheUtil;
import com.chyong.iptv.utils.DataUtil;
import com.kk.taurus.ijkplayer.IjkPlayer;
import com.kk.taurus.playerbase.config.PlayerLibrary;
import com.tencent.bugly.Bugly;

import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class MainActivity extends AppCompatActivity implements IMediaPlayer.OnPreparedListener {

    private long[] hits = new long[2];

    private SurfaceView ijkView;
    private View ctlView;
    private VerticalGridView channelView;
    private IjkMediaPlayer ijkMediaPlayer;

    private ChannelAdapter channelAdapter;
    private List<Channel> channels = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initAction();
    }

    private void initView() {
        ijkView = findViewById(R.id.ijk_view);
        ctlView = findViewById(R.id.ctl_view);
        channelView = findViewById(R.id.channel_view);
    }

    private void initData() {
        Bugly.init(this,"64b0759851", false);
        PlayerLibrary.init(this);
        IjkPlayer.init(this);
        channelAdapter = new ChannelAdapter(new ChannelAdapter.MyDiffCallback());
        channelView.setAdapter(channelAdapter);
    }

    private void initAction() {
        ijkView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ctlView.getVisibility() == View.GONE && channels.size() > 0) {
                    ctlView.setVisibility(View.VISIBLE);
                } else {
                    ctlView.setVisibility(View.GONE);
                }
            }
        });
        ijkView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                ijkView.getHolder().removeCallback(this);
                getIpInfo();
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
            }
        });
        channelView.setOnChildViewHolderSelectedListener(new OnChildViewHolderSelectedListener() {
            @Override
            public void onChildViewHolderSelected(RecyclerView parent, RecyclerView.ViewHolder child, int position, int subposition) {
                super.onChildViewHolderSelected(parent, child, position, subposition);
                if (CacheUtil.getInstance(MainActivity.this).getChannelPosition() != position) {
                    play(position);
                }
            }
        });
    }

    private void getIpInfo() {
        //对频道列表处理
        String url = "https://myip.ipip.net";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                getChannels("移动");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String ipInfo = response.body().string();
                    if (ipInfo.contains("电信")) {
                        getChannels("电信");
                    } else if (ipInfo.contains("联通")) {
                        getChannels("联通");
                    } else if (ipInfo.contains("移动")) {
                        getChannels("移动");
                    } else {
                        onFailure(null, null);
                    }
                } else {
                    onFailure(null, null);
                }

            }
        });
    }

    private void getChannels(String name) {
        String url = "https://gitee.com/chyong/iptv/raw/master/app/src/main/assets/data@" + name;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                setChannel(DataUtil.getLocalChannel(name, MainActivity.this));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String data = response.body().string();
                    setChannel(DataUtil.DataToChannels(data));
                } else {
                    onFailure(null, null);
                }
            }
        });
    }

    private void setChannel(List<Channel> list) {
        channels = list;
        channelAdapter.submitList(channels);
        int position = (CacheUtil.getInstance(this).getChannelPosition() + channels.size()) % channels.size();
        play(position);
    }

    private void play(int position) {
        if (ijkMediaPlayer != null) {
            ijkMediaPlayer.stop();
            ijkMediaPlayer.release();
        }
        try {
            CacheUtil.getInstance(this).setChannelPosition(position);
            channelView.setSelectedPosition(position);
            String url = channels.get(position).getUrl();
            //优化Options
            ijkMediaPlayer = new IjkMediaPlayer();
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", 100L);
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_clear", 1);
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1L);
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", 10240L);
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1L);
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-hevc", 1);
            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0L);
            ijkMediaPlayer.setOnPreparedListener(this);
            ijkMediaPlayer.setDataSource(url);
            ijkMediaPlayer.prepareAsync();
        } catch (IOException e) {
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK: //返回键
                if (ctlView.getVisibility() == View.VISIBLE) {
                    ctlView.setVisibility(View.GONE);
                } else if (ctlView.getVisibility() == View.GONE) {
                    System.arraycopy(hits, 1, hits, 0, hits.length - 1);
                    hits[hits.length - 1] = System.currentTimeMillis();
                    if (hits[0] >= (System.currentTimeMillis() - 1000)) {
                        //2次点击之后执行
                        finish();
                    } else {
                        Toast.makeText(this, "再按一次返回键关闭", Toast.LENGTH_LONG).show();
                    }
                }
                return true;
            case KeyEvent.KEYCODE_DPAD_CENTER:
                if (ctlView.getVisibility() == View.GONE && channels.size() > 0) {
                    ctlView.setVisibility(View.VISIBLE);
                }
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
            case KeyEvent.KEYCODE_CHANNEL_UP: //节目+
                if (ctlView.getVisibility() == View.GONE && channels.size() > 0) {
                    int up = (CacheUtil.getInstance(this).getChannelPosition() + 1 + channels.size()) % channels.size();
                    play(up);
                }
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
            case KeyEvent.KEYCODE_CHANNEL_DOWN: //节目-
                if (ctlView.getVisibility() == View.GONE && channels.size() > 0) {
                    int down = (CacheUtil.getInstance(this).getChannelPosition() - 1 + channels.size()) % channels.size();
                    play(down);
                }
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT: //音量+
                if (ctlView.getVisibility() == View.GONE && channels.size() > 0) {
                    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
                    audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);
                }
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT: //音量-
                if (ctlView.getVisibility() == View.GONE && channels.size() > 0) {
                    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
                    audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
                }
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onPrepared(IMediaPlayer iMediaPlayer) {
        ijkMediaPlayer.setDisplay(ijkView.getHolder());
        ijkMediaPlayer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ijkMediaPlayer != null) {
            ijkMediaPlayer.stop();
            ijkMediaPlayer.release();
        }
    }

}